﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using System.Net;
using System.Xml.Linq;
using SuperInterMarket.Mail;
using System.IO;

namespace SuperInterMarket
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private static string sendModel = "";//发送模式
        private static int toSize = 0; //收件箱地址数目


        private void SendMailBt_Click(object sender, EventArgs e)
        {

            string toAddress = ReceiveTxt.Text;
            if (string.IsNullOrEmpty(toAddress))
            {
                MessageBox.Show("收件人不能为空");
                return;
            }
            string fromAddress = SenderTxt.Text;
            if (string.IsNullOrEmpty(fromAddress))
            {
                MessageBox.Show("发件人不能为空");
                return;
            }
            string subject = SubjectTxt.Text;
            if (string.IsNullOrEmpty(subject))
            {
                MessageBox.Show("主题不能为空");
                return;
            }
            XDocument mailConfigDoc = XDocument.Load(SysConstants.MailConfigFile);
            XElement docconfig = mailConfigDoc.Root;
            sendModel = docconfig.Element("sendmodel").Value;
            int sendNum = int.Parse(docconfig.Element("sendnum").Value);
            bool isssl = docconfig.Element("isssl").Value == "1" ? true : false;

            MailAddress fromMailAddress = new MailAddress(fromAddress);
            MailMessage message = this.htmlEditor1.XMailMessage;
            message.Headers.Add("Disposition-Notification-To", fromMailAddress.Address);
            message.Headers.Add("X-Website", "http://www.xinglongjian.com");
            message.Headers.Add("ReturnReceipt", "1");
            message.ReplyToList.Add(fromAddress);
            message.Subject = subject;
            ////如果发送失败，SMTP 服务器将发送 失败邮件告诉我   
            message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
            message.From = fromMailAddress;

            //添加附件 
            if (!string.IsNullOrEmpty(attachTxt.Text))
            {
                string path = Application.StartupPath + "/" + attachTxt.Text;
                Attachment attach = new Attachment(path);

                attach.Name = attachTxt.Text;//Path.GetFileNameWithoutExtension(imagePath);
                message.Attachments.Add(attach);
            }


            XDocument doc = XDocument.Load(SysConstants.FromAddressFile);
            XElement config = doc.Element("config");

            XElement thisFrom = config.Elements("from").Where(c => c.Element("email").Value == fromAddress).SingleOrDefault();
            string defaultHost = "";
            int defaultPort = 0;
            string username = "";
            string password = "";
            if (thisFrom != null)
            {
                string severtype = thisFrom.Element("servertype").Value;
                username = thisFrom.Element("username").Value;
                password = thisFrom.Element("password").Value;


                XDocument serverDoc = XDocument.Load(SysConstants.MailServerFile);
                XElement serverConfig = serverDoc.Element("config");


                XElement thisServerType = serverConfig.Elements("server").Where(c => c.Attribute("type").Value == severtype).SingleOrDefault();
                if (thisServerType != null)
                {
                    defaultHost = thisServerType.Element("name").Value;
                    defaultPort = int.Parse(thisServerType.Element("port").Value);
                }


            }
            SmtpClient client = new SmtpClient(defaultHost, defaultPort);
            client.Credentials = new NetworkCredential(username, password);
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.EnableSsl = isssl;
            ////异步发送完成时的处理事件   


            if (sendModel.Equals("onetoone"))
            {
                //一对一
                string[] toss = toAddress.Split(new Char[] { ';' });
                toSize = toss.Length;
                //client.SendCompleted += new SendCompletedEventHandler(smtp_SendCompleted);
                foreach (var item in toss)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        message.To.Clear();
                        message.To.Add(item);
                        ////异步发送
                        for (int i = 0; i < sendNum; i++)
                        {
                            //client.SendAsync(message, null);
                            client.Send(message);
                        }


                    }
                }
            }
            else
            {
                //一对多
                //client.SendCompleted += new SendCompletedEventHandler(smtp_SendCompleted);
                string[] tos = toAddress.Split(new Char[] { ';' });
                if (tos.Length > 0)
                {
                    foreach (var item in tos)
                    {
                        if (!string.IsNullOrEmpty(item))
                        {
                            message.To.Add(item);
                        }

                    }
                }
                for (int i = 0; i < sendNum; i++)
                {

                    client.Send(message);
                }
            }
            MessageBox.Show("发送成功");
        }

        int i = 0;
        void smtp_SendCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (sendModel.Equals("onetoone"))
            {
                i++;
                if (e.Cancelled)
                {
                    MessageBox.Show("发送被取消");
                }
                else
                {
                    if (e.Error == null)
                    {
                        if (i == toSize)
                        {
                            MessageBox.Show("发送成功");
                        }

                    }
                    else
                    {
                        MessageBox.Show("发送失败： " + e.Error.Message);
                    }
                }
            }
            else
            {
                if (e.Cancelled)
                {
                    MessageBox.Show("发送被取消");
                }
                else
                {
                    if (e.Error == null)
                    {
                        MessageBox.Show("发送成功");
                    }
                    else
                    {
                        MessageBox.Show("发送失败： " + e.Error.Message);
                    }
                }
            }

        }

        private void MailConfigToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MailConfig defaultfrom = new MailConfig();
            defaultfrom.ShowDialog();
        }

        private void FromAddCheckBox_Click(object sender, EventArgs e)
        {
            if (FromAddCheckBox.Checked == true)
            {
                //FromAddCheckBox.Checked = true;
                //默认时 选择第一个
                SenderTxt.ReadOnly = true;
                XDocument doc = XDocument.Load(SysConstants.FromAddressFile);
                XElement config = doc.Element("config");
                XElement firstfrom = config.Elements("from").First();
                SenderTxt.Text = firstfrom.Element("email").Value;
            }
            else
            {
                //FromAddCheckBox.Checked = false;
                SenderTxt.ReadOnly = false;
                SenderTxt.Text = string.Empty;
            }
        }

        private void ServerConfigToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ServerManage sManage = new ServerManage();
            sManage.ShowDialog();
        }

        private void AddReceiveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToAddressManage toAddress = new ToAddressManage();
            toAddress.ShowDialog();
        }

        private void SelectToBt_Click(object sender, EventArgs e)
        {

        }

        private void AllAddressCheckBox_Click(object sender, EventArgs e)
        {
            if (AllAddressCheckBox.Checked == true)
            {
                ReceiveTxt.ReadOnly = true;
                XDocument doc = XDocument.Load(SysConstants.ToAddressFile);
                XElement config = doc.Element("config");
                List<XElement> allTos = config.Elements("toadd").ToList();
                if (allTos.Count > 0)
                {
                    StringBuilder sbuf = new StringBuilder();
                    foreach (var item in allTos)
                    {
                        sbuf.Append(item.Attribute("email").Value).Append(";");
                    }
                    ReceiveTxt.Text = sbuf.ToString();
                }
            }
            else
            {
                //FromAddCheckBox.Checked = false;
                ReceiveTxt.ReadOnly = false;
                ReceiveTxt.Text = string.Empty;
            }
        }

        private void FromAddressToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FromAddressManage from = new FromAddressManage();
            from.ShowDialog();
        }

        string fileName = "";
        string fileType = "";
        string fileSize = "";
        byte[] file;
        private void AttanchBt_Click(object sender, EventArgs e)
        {
            string strfile = "";
            OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
            OpenFileDialog1.Filter = "All files (*.*)|*.*|(*.pdf)|*.pdf|(*.xls)|*.xls|(*.doc)|*.doc|(*.jpg)|*.jpg";
            OpenFileDialog1.FilterIndex = 0;
            OpenFileDialog1.Title = "";
            OpenFileDialog1.Multiselect = false;
            if (OpenFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if (OpenFileDialog1.FileName.Length != 0)
                {
                    strfile = OpenFileDialog1.FileName;//获取文件路径
                    OpenFileDialog1.AddExtension = true;
                    fileName = Path.GetFileName(strfile);//获取文件名
                    fileType = fileName.Substring(fileName.IndexOf(".") + 1);
                    FileInfo fi = new FileInfo(strfile);
                    FileStream fs = fi.OpenRead();
                    fileSize = (fi.Length / 1024) + " KB";
                    byte[] bytes = new byte[fs.Length];
                    fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
                    file = bytes;
                    ReadFile();
                }
                else
                {
                    MessageBox.Show("请重新选择！");
                    return;
                }
            }
        }

        private void ReadFile()
        {
            attachTxt.Text = fileName;
            //txtFileType.Text = fileType;
            string path = Application.StartupPath + "//" + fileName;
            MemoryStream ms = new MemoryStream(file, 0, file.Length);
            StreamReader sr = new StreamReader(ms, System.Text.Encoding.GetEncoding("gb2312"));
            //webBrowser1.DocumentText = sr.ReadToEnd();
            //if (!File.Exists(upload))
            //{
            //    File.Create(upload);
            //}
            //string path=upload+fileName;
            if (File.Exists(path))
            {
                //存在就删除该文件
                File.Move(path, Application.StartupPath + "//" + fileName);
                File.Delete(Application.StartupPath + "//" + fileName);
            }

            //实例文件流对象，并创建临时PDF文件
            FileStream fs = new FileStream(path, FileMode.Create);
            //向文件流内写入数据库读取到的二进制数组
            fs.Write(file, 0, file.Length);
            //将文件对象设置为隐藏文件
            File.SetAttributes(path, FileAttributes.Hidden);
            long d = fs.Length;
            fs.Close();
            fs.Dispose();
            sr.Close();
            sr.Dispose();
            ms.Close();
            ms.Dispose();
            ////实例URI对象。得到临时创建的PDF文件地址
            //Uri url = new Uri(path);
            ////指定WebBrowser对象的URL 属性
            //webBrowser1.Url = url;
        }



        private void GetMailBt_Click(object sender, EventArgs e)
        {
            int Total = WebRichTextBox.Text.Length;
            int Percent = Total / 100;
            Console.WriteLine(WebRichTextBox.Text.Length);
            Console.WriteLine("1% = " + Percent);
            int At;
            int Start = 0;
            int End = 0;
            MailProgressBar.Visible = true;
            for (int c = 0; c < WebRichTextBox.Text.Length; c++)
            {
                WebRichTextBox.Select(c, 1);
                if (WebRichTextBox.SelectedText == "@")
                {
                    At = WebRichTextBox.SelectionStart;
                    for (int b = At; b >= 0; b--)
                    {
                        WebRichTextBox.Select(b, 1);
                        if (WebRichTextBox.SelectedText == " " || WebRichTextBox.SelectedText == "<" || WebRichTextBox.SelectedText == "," || WebRichTextBox.SelectedText == ">")
                        {
                            Start = WebRichTextBox.SelectionStart + 1;
                            break;
                        }
                    }
                    for (int a = At; a <= WebRichTextBox.Text.Length; a++)
                    {
                        WebRichTextBox.Select(a, 1);
                        if (WebRichTextBox.SelectedText == " " || WebRichTextBox.SelectedText == "<" || WebRichTextBox.SelectedText == "," | WebRichTextBox.SelectedText == ">")
                        {
                            End = WebRichTextBox.SelectionStart;
                            break;
                        }
                    }
                    WebRichTextBox.Select(Start, End - Start);
                    MaillistBox.Items.Add(WebRichTextBox.SelectedText);
                }
                MailProgressBar.Value = (c / Percent);
                LoadLabel.Text = "当前状态：Parsing file..." + c / Percent + "%";
                Console.WriteLine(c / Percent);
            }
            LoadLabel.Text = "当前状态：Success! " + MaillistBox.Items.Count + " items parsed!";
        }


        private void UrlBt_Click(object sender, EventArgs e)
        {
            LoadLabel.Text = "当前状态:<B>Loading file...</B>";
            MailWebBrowser.Navigate(UrlTxt.Text);
            MailWebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(MailWebBrowser_DocumentCompleted);
           
        }
        private void MailWebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            WebRichTextBox.Text = MailWebBrowser.Document.Body.InnerHtml;
            LoadLabel.Text = "当前状态:<B>File loaded!</B>";
        }
    }
}


